<template>
  <div class="DeptPicker">
    <a-input-search v-model:value="searchKey" placeholder="输入部门关键字搜索" style="margin-bottom: 12px"/>
    <a-checkbox-group :value="checkedList" @change="plainOptionsChange" :options="plainOptions"/>
    <a-spin :spinning="loading">
      <div ref="box" class="box">
        <base-tree
            :class="{ hideCheckBox: !props.showCheckBox }"
            :check-strictly="true"
            auto-expand-parent
            ref="tree"
            v-model:expandedKeys="expandedKeys"
            v-model:checkedKeys="checkedKeys"
            :tree-data="treeData"
            :field-names="treeFieldNames"
            checkable
            :selectable="false"
            @check="treeCheck"
            @expand="handleExpand"
        >
          <template #title="item">
            <div
                :class="{ highLightChecked: item.checked && props.highLightChecked, itemName: true, isStop: item.status === '1' }">
              {{ item.name }}
            </div>
          </template>
        </base-tree>
      </div>
    </a-spin>
  </div>
</template>
<script setup name="DeptPicker" lang='ts'>
import orgApi from '@/api/sys/orgApi'
import BaseTree from '@/components/BaseTree/BaseTree'
import {listToTree, trans} from "@/utils/util.ts";

const plainOptions = ['显示全部', '停用', '启用']
const checkedList = ref(['显示全部'])
const tree = ref()
const props = defineProps({
  multiple: {
    type: Boolean,
    default: () => false
  },
  showCheckBox: {
    type: Boolean,
    default: () => false
  },
  highLightChecked: {
    type: Boolean,
    default: () => true
  },
  depts: {
    type: Object,
    default: () => []
  }
})
let searchKey = ref('')
const emit = defineEmits({
  selectedDeptNodes: undefined,
  'update:depts': undefined
})
let expandedKeys = ref([])
let checkedKeys = ref({})
const plainOptionsChange = (val) => {
  checkedList.value = [val[0]]
  treeData.value = []
  onOpen()
}
let checkedNodes = computed({
  get: () => {
    return props.depts
  },
  set: (val) => {
    emit('update:depts', val)
  }
})
let loading = ref(true)
const treeData = ref([])
const transData = ref([])
const treeFieldNames = {children: 'children', title: 'name', key: 'id'}
const closeChildren = (node) => {
  let keys = JSON.parse(JSON.stringify(expandedKeys.value))
  expandedKeys.value = keys.filter((res) => {
    return res != node.id
  })
  if (node && node.hasOwnProperty('children') && node.children && node.children.length > 0) {
    node.children.forEach((res) => {
      closeChildren(res)
    })
  }
}
const handleExpand = (keys, {expanded, node}) => {
  if (expanded) {
    expandedKeys.value.push(node.key)
  } else {
    closeChildren(node)
  }
}
const treeCheck = (_checkedKeys, e) => {
  let {checked, checkedNodesPositions, event, halfCheckedKeys, node} = e
  let copycheckedNodes = JSON.parse(JSON.stringify(checkedNodes.value))
  if (props.multiple) {
    copycheckedNodes = e.checkedNodes
  } else {
    if (!!_checkedKeys && !!_checkedKeys.checked) {
      copycheckedNodes = [e.checkedNodes[e.checkedNodes.length - 1]]
      checkedKeys.value.checked = [_checkedKeys.checked[_checkedKeys.checked.length - 1]]
    }
  }
  checkedNodes.value = JSON.parse(JSON.stringify(copycheckedNodes))
  emit('selectedDeptNodes', copycheckedNodes)
}
// 打开此界面需要具体某条菜单的id跟选中的
const onOpen = () => {
  loading.value = true
  // const treeData = data.data;
  setTimeout(() => {
    let status = undefined
    switch (checkedList.value[0]) {
      case '显示全部': {
        break
      }
      case '停用': {
        status = '1'
        break
      }
      case '启用': {
        status = '0'
        break
      }
    }
    orgApi.orgTree().then((res) => {
      if (res !== null) {
        transData.value = trans(JSON.parse(JSON.stringify(res))).filter((res) => {
          return checkedList.value[0] == '显示全部' ? true : checkedList.value[0] == '停用' ? res.status === '1' : res.status === '0'
        })
        treeData.value = listToTree(
            trans(
                JSON.parse(
                    JSON.stringify(
                        transData.value.map((mres) => {
                          if (checkedNodes.value.length > 0) {
                            var target = checkedNodes.value.find((fres) => {
                              return fres.id == mres.id
                            })
                            if (target && target.hasOwnProperty('delete')) {
                              mres.disableCheckbox = !target.delete
                            } else {
                              mres.disableCheckbox = false
                            }
                            checkedKeys.value.checked = checkedNodes.value.map((res) => {
                              return res.id
                            })
                          } else {
                            mres.disableCheckbox = false
                          }
                          return mres
                        })
                    )
                )
            )
        )
        if (checkedKeys.value.checked && checkedKeys.value.checked.length > 0) {
          expandedKeys.value = checkedKeys.value.checked
        } else {
          expandedKeys.value = treeData.value.reduce((p, c, ci) => {
            if (p.length < 1) {
              p = [c.id]
            }
            if (c.hasOwnProperty('children') && c.children.length > 0) {
              c.children.forEach((res) => {
                p.push(res.id)
              })
            }
            return p
          }, [])
        }
        loading.value = false
      }
    })
  }, 500)
}
onMounted(() => {
  onOpen()
})
watch(
    () => searchKey.value,
    (val) => {
      if (val && val != '') {
        treeData.value = listToTree(
            transData.value.filter((res) => {
              return res.name.indexOf(val) > -1
            })
        )
      } else {
        treeData.value = listToTree(transData.value)
      }
    }
)
</script>
<style scoped lang="less">
.DeptPicker {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  height: 100%;
  overflow: hidden;

  :deep(.hideCheckBox) {
    .ant-tree-checkbox {
      display: none !important;
    }

    .ant-tree-switcher {
      left: 12px;
    }
  }

  :deep(.ant-spin-nested-loading) {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .ant-spin-container {
      height: 100%;
      overflow: hidden;

      .box {
        width: 100%;
        min-height: 100px;
        height: 100%;
        overflow-y: auto;

        :deep(.ant-list-item) {
          &:hover {
            background: #e6f7ff;
            color: #1890ff;
          }
        }

        .ant-tree-node-content-wrapper {
          .ant-tree-title {
            .itemName {
              padding: 0 6px;
              font-size: 16px;
              line-height: 24px;
            }

            .highLightChecked {
              background: #1890ff;
              color: #fff;
              border-radius: 3px;
            }

            .isStop {
              background: #d9d9d940;
              color: #4446;
            }
          }
        }
      }
    }
  }
}
</style>
